package com.lagou.ModelTest4.Third;

import java.util.concurrent.locks.ReentrantLock;

class Demo{}
public class TrainRunnableTest implements Runnable{
    private int balance;//用于描述火车票的数量
    private Demo dm=new Demo();
    private ReentrantLock lock=new ReentrantLock();//准备了一把锁
    public  TrainRunnableTest(){}
    public  TrainRunnableTest(int balance){
        setBalance(balance);
    }
    public int getBalance(){
        return balance;
    }
    public void setBalance(int balance){
        this.balance=balance;
    }
    @Override
    public /*synchronized*/ void run() {
        //开始加锁
        lock.lock();
        //由源码可知:最终是art对象来调用run方法，因此当前正在调用的对象就是art,也就是说this就是art
        //synchronized (this) {
        System.out.println("线程" + Thread.currentThread().getName() + "已启动...");
        //synchronized (dm) {
        //synchronized (new Demo()) {  //锁不住 要求必须是同一个对象
        //1.模拟从后台查询火车票数的过程
        int temp = getBalance();
        //2.模拟取票20张的过程
        if (temp >= 20) {
            System.out.println("正在取票，不要急...");
            temp = temp - 20;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("请取走您的火车票!");
        } else {
            System.out.println("火车票不足!");
        }
        //3.模拟将最新的火车票数写入到后台
        setBalance(temp);
        lock.unlock();//实现解锁
    }


    public static void main(String[] args) {
        TrainRunnableTest art=new TrainRunnableTest(100);
        Thread t1=new Thread(art);
        Thread t2=new Thread(art);
        Thread t3=new Thread(art);
        t1.start();
        t2.start();
        t3.start();
        System.out.println("主线程开始等待...");
        try {
            t1.join();
            //t2.start();//等待线程一取款操作结束后再启动线程二
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("最终的火车票数为:"+art.getBalance());//40
    }
}